<script lang="ts" setup>
import type { UploadFile } from 'ant-design-vue';

import type { VbenFormSchema } from '#/adapter/form';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { importTender, uploadFile } from '#/api';

type ImportData = {
  file: UploadFile[];
};

const formData = ref<ImportData>({ file: [] });
const schema: VbenFormSchema[] = [
  {
    component: 'Upload',
    componentProps: {
      // 更多属性见：https://ant.design/components/upload-cn
      accept: '.xls,.xlsx,.csv',
      // 自动携带认证信息
      customRequest: uploadFile,
      maxCount: 1,
      multiple: false,
    },
    fieldName: 'file',
    formItemClass: 'col-span-2 md:col-span-2',
    label: '招标信息文件',
  },
];

const [Form, formApi] = useVbenForm({
  commonConfig: {
    colon: true,
    formItemClass: 'col-span-2 md:col-span-1',
  },
  schema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2 gap-x-4',
});

const [Modal, modalApi] = useVbenModal({
  onConfirm: onSubmit,
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<ImportData>();
      if (data) {
        formData.value = data;
        formApi.setValues(formData.value);
      } else {
        formApi.resetForm();
      }
    }
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    modalApi.lock();
    const data = await formApi.getValues<ImportData>();
    const file = data.file[0];
    if (file) {
      try {
        await importTender({ file_id: file.response?.id });
        modalApi.close();
      } finally {
        modalApi.unlock();
      }
    }
  }
}
</script>
<template>
  <Modal class="w-full max-w-[800px]" title="导入">
    <Form class="mx-4" layout="vertical" />
  </Modal>
</template>
